import * as THREE from 'three';
import { onBeforeUnmount } from 'vue';

type UseRaycasterParams = {
  getOrbitControlsCamera: () => THREE.Camera;
  getScene: () => THREE.Scene;
};

export default function useRaycaster(data: UseRaycasterParams) {
  const raycaster = new THREE.Raycaster();

  function handleMouseDown(event) {
    let x: number;
    let y: number;
    if (event.changedTouches) {
      x = event.changedTouches[0].pageX;
      y = event.changedTouches[0].pageY;
    } else {
      x = event.clientX;
      y = event.clientY;
    }
    const mousePostion = {
      x: (x / window.innerWidth) * 2 - 1,
      y: -(y / window.innerHeight) * 2 + 1,
    };

    checkIntersection(mousePostion);
  }
  function checkIntersection(mousePostion) {
    raycaster.setFromCamera(mousePostion, data.getOrbitControlsCamera());
    const intersects = raycaster.intersectObjects(data.getScene().children, true);
    if (intersects.length > 0) {
      const obj = intersects[0].object;
      const point = intersects[0].point;
      const name = obj.name;
      console.log(name, obj, point);
    }
  }

  onBeforeUnmount(() => {});

  return {
    handleMouseDown,
    checkIntersection,
  };
}
